package com.gkt.ec.cms.activity.task;

import com.gkt.ec.cms.activity.AppConstant;
import com.gkt.ec.cms.activity.model.domain.CustomerActivityEntity;
import com.gkt.ec.cms.activity.model.domain.MarketActivityEntity;
import com.gkt.ec.cms.activity.service.ActivityService;
import com.gkt.ec.cms.task.support.SmsSender;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;

/**
 * 一个活动的发送短信任务
 *
 * @author Huzl
 * @version 1.0.0
 */
public class SendSmsTask implements Runnable {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private MarketActivityEntity activityEntity;
    private ScheduledFuture scheduledFuture;
    private volatile boolean canceled = false;
    private TaskStatusCallback taskStatusCallback;
    private ActivityService activityService;
    private SmsSender smsSender;
    private Executor sendSmsExecutor;

    public SendSmsTask(MarketActivityEntity activityEntity, TaskStatusCallback taskStatusCallback, ActivityService activityService) {
        this.activityEntity = activityEntity;
        this.taskStatusCallback = taskStatusCallback;
        this.activityService = activityService;
    }

    public SendSmsTask setActivityService(ActivityService activityService) {
        this.activityService = activityService;
        return this;
    }

    public SendSmsTask setSmsSender(SmsSender smsSender) {
        this.smsSender = smsSender;
        return this;
    }

    public SendSmsTask setSendSmsExecutor(Executor sendSmsExecutor) {
        this.sendSmsExecutor = sendSmsExecutor;
        return this;
    }

    public void setScheduledFuture(ScheduledFuture scheduledFuture) {
        this.scheduledFuture = scheduledFuture;
    }

    public void run() {
        taskStatusCallback.beginTask(activityEntity.getId());
        List<CustomerActivityEntity> customerActivityList = activityService.queryAllCustomerActivity(activityEntity.getId());
        for (int i = 0; i < customerActivityList.size() && !canceled; i++) {
            final CustomerActivityEntity customerActivityEntity = customerActivityList.get(i);
            if (customerActivityEntity.getSmsSendStatus() != AppConstant.SendSmsStatus.UNSEND)
                continue;
            final boolean isLast = ((i + 1) == customerActivityList.size());
            sendSmsExecutor.execute(new Runnable() {
                public void run() {
                    sendSms(customerActivityEntity, isLast);
                }
            });
        }

    }

    private void sendSms(CustomerActivityEntity customerActivityEntity, boolean isLast) {
        if (canceled) return;
        String smsContent = buildSmsContent(customerActivityEntity);
        String tel = customerActivityEntity.getCustomerTel();
        try {
            smsSender.send(tel, smsContent);
            taskStatusCallback.sentSms(activityEntity.getId(), customerActivityEntity, true);
        } catch (Exception e) {
            taskStatusCallback.sentSms(activityEntity.getId(), customerActivityEntity, false);
            logger.warn("SendSmsTask exception tel:" + tel + ",content:" + smsContent, e);
        }

        if (isLast && !canceled) {
            taskStatusCallback.endTask(activityEntity.getId());
        }
    }

    /**
     * 撤销中断短信发送任务
     */
    public void cancel() {
        this.canceled = true;
        scheduledFuture.cancel(true);
    }

    private String buildSmsContent(CustomerActivityEntity customerActivityEntity) {
        Map<String, String> values = new HashMap<String, String>();
        values.put("activityName", activityEntity.getActivityName());
        values.put("vehicleLicense", customerActivityEntity.getVehicleLicense());
        values.put("customerTel", customerActivityEntity.getCustomerTel());
        values.put("activityId", String.valueOf(customerActivityEntity.getActivityId()));
        values.put("customerId", customerActivityEntity.getCustomId());
        values.put("customerActivityId", String.valueOf(customerActivityEntity.getId()));

        //替换活动url中的参数
        String url = replaceTemplate(activityEntity.getActivityUrl(), values);
        values.put("url", url);

        String smsContent = activityEntity.getSmsTemplate();
        return replaceTemplate(smsContent, values);
    }

    private String replaceTemplate(String str, Map<String, String> variables) {
        if (str == null) return null;
        for (Map.Entry<String, String> entry : variables.entrySet()) {
            if (!str.contains("{") && !str.contains("}"))
                return str;
            if (entry.getValue() != null)
                str = StringUtils.replace(str, "{" + entry.getKey() + "}", entry.getValue());
        }
        return str;
    }

}
